package com.example.article.controller.v1;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.apis.behaviour.IBehaviourClient;
import com.example.apis.wemedia.IWemediaClient;
import com.example.article.mapper.*;
import com.example.article.service.ApArticleContentService;
import com.example.article.service.ApArticleService;
import com.example.common.constants.ArticleConstants;
import com.example.model.article.dtos.ArticleHomeDto;
import com.example.model.article.pojos.*;
import com.example.model.common.dtos.ResponseResult;
import com.example.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RequestMapping("/api/v1/article")
@RestController
public class ArticleHomeController {

    @Autowired
    private ApArticleContentService apArticleContentService;

    @Autowired
    private ApArticleService apArticleService;

    @Autowired
    private IWemediaClient iWemediaClient;


    @PostMapping("/getChannels")
    public ResponseResult getChannels(){
        return iWemediaClient.getChannels();
    }
    /**
     * 加载首页
     * @param dto
     * @return
     */
    @PostMapping("/load")
    public ResponseResult load(@RequestBody(required = false) ArticleHomeDto dto){
        //        return apArticleService.load(dto, ArticleConstants.LOADTYPE_LOAD_MORE);
        return apArticleService.load2(dto, ArticleConstants.LOADTYPE_LOAD_MORE,true);
    }

    @PostMapping("/loadRecommend")
    public ResponseResult loadRecommendData(HttpServletRequest request){

        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();

        return apArticleService.loadRecommendData(userId);
    }

    /*@PostMapping("/load")
    public ResponseResult load(@RequestBody(required = false) ArticleHomeDto dto){
        return apArticleService.load(dto, ArticleConstants.LOADTYPE_LOAD_MORE);
    }*/

    @PostMapping("/loadmore")
    public ResponseResult loadmore(@RequestBody(required = false) ArticleHomeDto dto){
        return apArticleService.load(dto, ArticleConstants.LOADTYPE_LOAD_MORE);
    }

    @PostMapping("/loadnew")
    public ResponseResult loadnew(@RequestBody(required = false) ArticleHomeDto dto){
        return apArticleService.load(dto, ArticleConstants.LOADTYPE_LOAD_NEW);
    }

    @Autowired
    private IBehaviourClient iBehaviourClient;

    @GetMapping("/articleContent/{id}")
    public ResponseResult getApArticleContentById(@PathVariable String id,HttpServletRequest request){

        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        LambdaQueryWrapper<ApArticleContent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApArticleContent::getArticleId,id);

        //浏览量+1
        LambdaQueryWrapper<ApArticle> apArticleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apArticleLambdaQueryWrapper.eq(ApArticle::getId,id);
        ApArticle apArticle = apArticleService.getOne(apArticleLambdaQueryWrapper);
        apArticle.setViews(apArticle.getViews()+1);
        apArticleService.updateById(apArticle);

        ApArticleContent articleContent = apArticleContentService.getOne(lambdaQueryWrapper);
        articleContent.setTitle(apArticle.getTitle());
        articleContent.setAuthorId(Math.toIntExact(apArticle.getAuthorId()));
        articleContent.setAuthorName(apArticle.getAuthorName());
        articleContent.setPublishTime(apArticle.getPublishTime());

        boolean isFollowed = iBehaviourClient.isFollowed(userId,Math.toIntExact(apArticle.getAuthorId()));
        articleContent.setFollowed(isFollowed);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("articleId",id);
        queryWrapper.eq("userId",userId);
        ApArticleThumb apArticleThumb = apArticleThumbMapper.selectOne(queryWrapper);
        if(apArticleThumb == null){
            articleContent.setLiked(false);
        }else {
            articleContent.setLiked(true);
        }

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("articleId",id);
        queryWrapper1.eq("userId",userId);
        ApUserCollection apUserCollection = apUserCollectionMapper.selectOne(queryWrapper1);
        if(apUserCollection == null){
            articleContent.setCollected(false);
        }else{
            articleContent.setCollected(true);
        }

        ApUserScore apUserScore = apUserScoreMapper.selectOne(queryWrapper1);
        if(apUserScore == null){
            ApUserScore apUserScore1 = new ApUserScore();
            apUserScore1.setScore(1.0);
            apUserScore1.setUserId(userId);
            apUserScore1.setArticleId(id);
            apUserScoreMapper.insert(apUserScore1);
        }else{
            apUserScore.setScore(apUserScore.getScore()+1.0);
            apUserScoreMapper.updateById(apUserScore);
        }

        return ResponseResult.okResult(articleContent);

    }

    @Autowired
    private ApUserCollectionMapper apUserCollectionMapper;

    @Autowired
    private ApUserScoreMapper apUserScoreMapper;

    @GetMapping("/articleCollection/{id}")
    public ResponseResult collectOneArticle(@PathVariable String id, HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        ApUserCollection apUserCollection = new ApUserCollection();
        apUserCollection.setUserId(userId);
        apUserCollection.setArticleId(Long.parseLong(id));
        apUserCollection.setCreatedTime(new Date());
        apUserCollectionMapper.insert(apUserCollection);

        ApArticle apArticle = apArticleService.getById(id);
        apArticle.setCollection(apArticle.getCollection()+1);
        apArticleService.updateById(apArticle);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("articleId",id);
        ApUserScore apUserScore = apUserScoreMapper.selectOne(queryWrapper);
        if(apUserScore == null){
            ApUserScore apUserScore1 = new ApUserScore();
            apUserScore1.setScore(6.0);
            apUserScore1.setUserId(userId);
            apUserScore1.setArticleId(id);
            apUserScoreMapper.insert(apUserScore1);
        }else{
            apUserScore.setScore(apUserScore.getScore()+6.0);
            apUserScoreMapper.updateById(apUserScore);
        }
        return ResponseResult.okResult("收藏成功");
    }

    @GetMapping("/articleUnCollection/{id}")
    public ResponseResult UncollectOneArticle(@PathVariable String id, HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper<ApUserCollection>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("articleId",id);
        apUserCollectionMapper.delete(queryWrapper);

        ApArticle apArticle = apArticleService.getById(id);
        apArticle.setCollection(apArticle.getCollection()-1);
        apArticleService.updateById(apArticle);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userId",userId);
        queryWrapper1.eq("articleId",id);
        ApUserScore apUserScore = apUserScoreMapper.selectOne(queryWrapper1);
        if(apUserScore == null){

        }else{
            apUserScore.setScore(apUserScore.getScore()-6.0);
            apUserScoreMapper.updateById(apUserScore);
        }

        return ResponseResult.okResult("取消收藏成功");
    }

    @GetMapping("/collectionList")
    public ResponseResult getCollectionList(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper<ApUserCollection>();
        queryWrapper.eq("userId",userId);

        return ResponseResult.okResult(apUserCollectionMapper.selectList(queryWrapper));
    }

    @Autowired
    private ApArticleThumbMapper apArticleThumbMapper;

    /*
    文章点赞
     */
    @PostMapping("/likeArticle/{id}")
    public ResponseResult likeArticle(@PathVariable("id") String id,HttpServletRequest request){
        ApArticle apArticle = apArticleService.getById(id);
        apArticle.setLikes(apArticle.getLikes()+1);
        apArticleService.updateById(apArticle);

        ApArticleThumb apArticleThumb = new ApArticleThumb();
        apArticleThumb.setArticleId(id);

        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        apArticleThumb.setUserId(userId);
        apArticleThumb.setCreatedTime(new Date());

        apArticleThumbMapper.insert(apArticleThumb);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("articleId",id);
        ApUserScore apUserScore = apUserScoreMapper.selectOne(queryWrapper);
        if(apUserScore == null){
            ApUserScore apUserScore1 = new ApUserScore();
            apUserScore1.setScore(4.0);
            apUserScore1.setUserId(userId);
            apUserScore1.setArticleId(id);
            apUserScoreMapper.insert(apUserScore1);
        }else{
            apUserScore.setScore(apUserScore.getScore()+4.0);
            apUserScoreMapper.updateById(apUserScore);
        }

        return ResponseResult.okResult("点赞成功");
    }

    /*
    文章点赞
     */
    @PostMapping("/unlikeArticle/{id}")
    public ResponseResult unlikeArticle(@PathVariable("id") String id,HttpServletRequest request){
        ApArticle apArticle = apArticleService.getById(id);
        apArticle.setLikes(apArticle.getLikes()-1);
        apArticleService.updateById(apArticle);



        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("articleId",id);
        queryWrapper.eq("userId",userId);

        apArticleThumbMapper.delete(queryWrapper);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userId",userId);
        queryWrapper1.eq("articleId",id);
        ApUserScore apUserScore = apUserScoreMapper.selectOne(queryWrapper1);
        if(apUserScore == null){

        }else{
            apUserScore.setScore(apUserScore.getScore()-4.0);
            apUserScoreMapper.updateById(apUserScore);
        }

        return ResponseResult.okResult("取消点赞成功");
    }

}
